<template>
  <div id="NewSubjectMajor">
    <!-- 顶部标签组件 -->
    <mytabs
      :tabDataList="tabDataList"
      :majorDataList="majorDataList"
      :activeName="activeName"
      @update:activeName="updateActiveName"
    />

    <!-- 表格组件，显示院校或专业数据 -->
    <el-table
      :data="!isMajor ? yxTableData : processedZyTableData"
      style="width: 100%"
      v-if="ruleType != 3"
    >
      <!-- 院校列，显示院校信息 -->
      <el-table-column
        prop="collegeName"
        label="院校"
        width="400"
        v-if="!isMajor"
      >
        <template #default="scope">
          <div class="font-weight-bold f18">
            {{ scope.row.collegeName }}
          </div>
          <div class="f12">
            {{ scope.row.collegeView }}
          </div>
        </template>
      </el-table-column>

      <!-- 专业列，显示专业信息 -->
      <el-table-column prop="majorName" label="专业" width="400" v-if="isMajor">
        <template #default="scope">
          <div class="font-weight-bold f18">
            {{ scope.row.majorName }}
          </div>
          <div class="f12">
            <div>
              <span>代码：{{ scope.row.majorCode }} </span
              ><span>所属门类：{{ scope.row.majorNameView }}</span>
            </div>
            <div>开设院校：{{ scope.row.countSummary.collegeCount }}所</div>
          </div>
        </template>
      </el-table-column>

      <!-- 最优组合列 -->
      <el-table-column prop="bestCombineName" label="最优组合" />

      <!-- 开设专业列 -->
      <el-table-column
        prop="countSummary.totalCount"
        label="开设专业"
        v-if="!isMajor"
      >
        <template #default="scope">
          <div class="df">
            <div>开设专业：</div>
            <div
              class="df curpoin"
              style="color: var(--color-text)"
              @click="openDialog(scope.row, 'offerAmajorRef')"
            >
              <div>{{ scope.row.countSummary.totalCount || '-' }}个</div>
              <div>
                <el-icon size="14" style="margin-top: 7px"
                  ><ArrowRight
                /></el-icon>
              </div>
            </div>
          </div>
        </template>
      </el-table-column>

      <!-- 专业匹配率列 -->
      <el-table-column
        prop="address"
        label="专业匹配率"
        v-if="!isMajor && ruleType !== '3'"
      >
        <template #default="scope">
          <div
            class="df curpoin"
            style="color: var(--color-text)"
            @click="openDialog(scope.row, 'ratioDialogRef')"
          >
            <div>专业匹配率</div>
            <div>
              <el-icon size="14" style="margin-top: 7px"
                ><ArrowRight
              /></el-icon>
            </div>
          </div>
        </template>
      </el-table-column>

      <!-- 匹配院校/匹配率列 -->
      <el-table-column
        prop="percentView"
        label="匹配院校/匹配率"
        width="300"
        v-if="isMajor"
      >
        <template #default="scope">
          <div class="df curpoin" style="color: var(--color-text)">
            <div @click="openDialog(scope.row, 'offerAmajorRef')">匹配专业</div>
            <div>/</div>
            <div class="df" @click="openDialog(scope.row, 'ratioDialogRef')">
              <div>{{ scope.row.percentView }}</div>
              <el-icon size="14"><ArrowRight /></el-icon>
            </div>
          </div>
        </template>
      </el-table-column>

      <!-- 选科列 -->
      <el-table-column label="选科" v-if="ruleType != 3">
        <template #default="scope">
          <div
            class="my-btn curpoin"
            @click="handleCollegeCheck(scope.row)"
            :class="scope.row.isSelected ? 'active' : ''"
          >
            {{ scope.row.isSelected ? '已选' : '选择' }}
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 路由等于3的情况，显示专业或院校的特定表格 -->
    <div v-else>
      <div v-if="isMajor">
        <!-- 专业表格 -->
        <el-table :data="subjectzyData" style="width: 100%">
          <el-table-column prop="collegeName" label="院校" />
          <el-table-column prop="professionName" label="专业" />
          <el-table-column prop="eduLevel" label="专业层次">
            <template #default="scope">
              {{ scope.row.eduLevel == 'ben' ? '本科' : '专科' }}
            </template>
          </el-table-column>
          <el-table-column prop="direction" label="招考方向">
            <template #default="scope">
              {{ scope.row.direction || '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="professions" label="包含专业">
            <template #default="scope">
              {{ scope.row.professions || '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="secondRequired" label="科目要求">
            <template #default="scope">
              {{
                scope.row.rule !== '0' ? scope.row.firstRequired : '--' || '-'
              }}
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-else>
        <!-- 院校表格 -->
        <el-table :data="subjectyxData" style="width: 100%">
          <el-table-column prop="collegeName" label="院校" />
          <el-table-column prop="bestCombineName" label="最优组合" />
          <el-table-column prop="totalCount" label="开设专业">
            <template #default="scope">
              <div class="df">
                <div>开设专业：</div>
                <div
                  class="df curpoin"
                  style="color: var(--color-text)"
                  @click="openDialog(scope.row, 'offerAmajorRef')"
                >
                  <div>
                    {{ get(scope.row, 'countSummary.totalCount', '-') }}个
                  </div>
                  <div>
                    <el-icon size="14" style="margin-top: 7px"
                      ><ArrowRight
                    /></el-icon>
                  </div>
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 百分比弹窗 -->
    <ratioDialog ref="ratioDialogRef" />

    <!-- 开设专业弹窗 -->
    <offerAmajor ref="offerAmajorRef" />
  </div>
</template>

<script setup>
// 导入所需模块和组件
import { ref, watch, onMounted } from 'vue';
import store from '@/store';
import mytabs from '../../../components/MyTabs';
import ratioDialog from './RatioDialog';
import offerAmajor from './OfferAmajor';
import { get } from 'lodash';
import { handleOpenDialog, sortAllCombineKeys, sortByCode } from './utils';
import {
  getSearchSchoolFilter,
  getAllMajor,
} from '@/api/selectSubject/subject';

// 路由信息
const emits = defineEmits(['updateIsMajor', 'getEmitContact']);

// 定义传入的属性
const {
  yxTableData,
  zyTableData,
  ruleType,
  isMajor,
  subjectzyData,
  subjectyxData,
} = defineProps({
  yxTableData: { type: Array, default: () => [] },
  zyTableData: { type: Array, default: () => [] },
  subjectzyData: { type: Array, default: () => [] },
  subjectyxData: { type: Array, default: () => [] },
  ruleType: { type: String, default: '0' },
  isMajor: { type: Boolean, default: false },
});

// 顶部筛选数据
const tabDataList = ref([{ tabsItem: [] }, { tabsItem: [{ content: [] }] }]);
const majorDataList = ref([]);
const activeName = ref('yx'); // 当前选中的选项卡
const processedZyTableData = ref([]); // 处理后的专业数组

// 更新选项卡的值
const updateActiveName = (tabName) => {
  activeName.value = tabName;
  getfiliterList();
  emits('updateIsMajor', tabName == 'zy'); // 通知父组件更新是否为专业
};

// 根据选项卡获取筛选数据
const getfiliterList = () => {
  activeName.value == 'yx' ? fetchSearchSchoolFilter() : fetchAllMajor();
};

// 获取院校筛选条件
const fetchSearchSchoolFilter = () => {
  getSearchSchoolFilter().then((res) => {
    if (res.data.code == 20000) {
      tabDataList.value = res.data.data;
    }
  });
};

// 获取专业筛选条件
const fetchAllMajor = () => {
  const data = { majorsBK: 1, deep: 2 };
  getAllMajor(data).then((res) => {
    if (res.data.code == 20000) {
      majorDataList.value = res.data.data.majorsBK;
      if (tabDataList.value[1] && tabDataList.value[1].tabsItem[0]) {
        tabDataList.value[1].tabsItem[0].content = [...res.data.data.majorsBK];
      }
    }
  });
};

// 打开弹窗
const ratioDialogRef = ref(null);
const offerAmajorRef = ref(null);
const openDialog = (row, refCode) => {
  handleOpenDialog(
    store,
    row,
    refCode,
    isMajor,
    ratioDialogRef,
    offerAmajorRef,
  );
};

// 点击列表选择
const handleCollegeCheck = (row) => {
  row = { ...row, isSelected: !row.isSelected };
  const { selectCollegeList, selectMarjorList } = store.getters.znxkInfo;
  const targetRows = isMajor ? selectMarjorList : selectCollegeList;
  if (row.isSelected) {
    targetRows.push(row);
  } else {
    const index = targetRows.findIndex((item) => item.id == row.id);
    if (index !== -1) targetRows.splice(index, 1);
  }
  store.dispatch(
    isMajor ? 'znxk/changeSelectMarjorList' : 'znxk/changeSelectCollegeList',
    [...targetRows],
  );
  store.dispatch('znxk/updateTableSelect', { isMajor, flag: true });
  store.dispatch('znxk/updateManualSelect', { isMajor, flag: false });
};
// 更新专业数组的匹配率
const updatePercentView = (tableData, code) => {
  tableData.forEach((item) => {
    if (item.allCombine && typeof item.allCombine === 'object') {
      const sortedAllCombine = sortAllCombineKeys(item.allCombine);
      item.percentView = sortedAllCombine[code]
        ? `${sortedAllCombine[code].percent}%`
        : '0%';
    }
  });
};
// 监听科目选择，更新专业数组的匹配率
// 监听科目选择变化
watch(
  () =>
    isMajor ? store.getters.znxkInfo.zySgID : store.getters.znxkInfo.yxSgID,
  (newValue) => {
    if (!newValue) return;
    const code = sortByCode(newValue); // 对新值排序
    // 获取vuex中选中的院校和专业
    const { selectMarjorList, selectCollegeList } = store.getters.znxkInfo;
    // 更新表格数据的匹配率
    updatePercentView(processedZyTableData.value, code);
    // 判断是否触发 'getEmitContact' 事件
    const listLength = isMajor
      ? selectMarjorList.length
      : selectCollegeList.length;
    if (!listLength) emits('getEmitContact', code);
  },
  { deep: true },
);

// 监听 zyTableData 的变化，更新 processedZyTableData
watch(
  () => zyTableData,
  (newValue) => {
    if (newValue) {
      processedZyTableData.value = newValue;
    }
  },
  { immediate: true, deep: true },
);

// 组件挂载时获取筛选数据
onMounted(() => {
  getfiliterList();
});
</script>

<style lang="scss" scoped>
#NewSubjectMajor {
  .my-btn {
    color: var(--color-text);
    width: 80px;
    text-align: center;
    border-radius: 4px;
    border: 1px solid var(--color-text);
  }
}
.active {
  background: var(--color-text);
  color: #fff !important;
}
</style>
